package com.sh.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.DefaultResponse;
import org.springframework.cloud.client.loadbalancer.EmptyResponse;
import org.springframework.cloud.client.loadbalancer.Request;
import org.springframework.cloud.client.loadbalancer.Response;
import org.springframework.cloud.loadbalancer.core.ReactorServiceInstanceLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.context.annotation.Configuration;
import reactor.core.publisher.Mono;

import java.time.LocalDate;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

//@Configuration
@Slf4j
public class DIYLoadBalance implements ReactorServiceInstanceLoadBalancer {

    private final ServiceInstanceListSupplier serviceInstanceListSupplier;

    public DIYLoadBalance(ServiceInstanceListSupplier serviceInstanceListSupplier) {
        this.serviceInstanceListSupplier = serviceInstanceListSupplier;
    }

    @Override
    public Mono<Response<ServiceInstance>> choose(Request request) {
        return serviceInstanceListSupplier.get(request).next().map(serviceInstances -> {
            return getInstanceResponse(serviceInstances);
        });
    }

    private Response<ServiceInstance> getInstanceResponse(List<ServiceInstance> serviceInstances) {
        log.info("自定义负载");
        if( serviceInstances.isEmpty() ){
            return new EmptyResponse();
        }
        int size = serviceInstances.size();
        if ( size == 1 ){
            return new DefaultResponse(serviceInstances.get(0));
        }
        int date = LocalDate.now().getDayOfMonth();
        Random random = new Random();
        int randomNum;
        if (date % 2 == 0) {
            do {
                randomNum = random.nextInt(size);
            }while (randomNum%2 != 0 );
            return new DefaultResponse(serviceInstances.get(randomNum));
        }else {
            do {
                randomNum = random.nextInt(size);
            }while (randomNum%2 == 0 );
            return new DefaultResponse(serviceInstances.get(randomNum));
        }
    }
}
